//
//  MemberPrepaidPhoneViewController.m
//  BaseFrame
//
//  Created by 吕金状 on 2017/8/9.
//  Copyright © 2017年 com.mxh. All rights reserved.
//

#import "MemberPrepaidPhoneViewController.h"
#import "MemberPrepaidPhoneTableViewCell.h"
#import "MembersPayTopUpView.h"

@interface MemberPrepaidPhoneViewController ()<UITableViewDelegate , UITableViewDataSource>
{
    int chooseIndexPath;
}
Strong UIView *headView;
Strong UITableView *tableView;
Strong NSMutableArray *dataArray; /**<*/
Strong UIImageView *titleImageView;
Strong UILabel *balanceLabel;//余额标题
Strong UILabel *moneyLabel; //余额
Strong UILabel *numberLabel;//卡号
Strong UIView *footView;

//支付宝支付-微信支付
- (void)payByALiWithHandle:(NSString *)orderString;
- (void)weiXinpay:(NSDictionary *)dic;

@end

//网络
@implementation MemberPrepaidPhoneViewController(NetWorking)

- (void)getData{
    [self showprogressHUD];
    NSDictionary *parameters = @{@"auId":[UserModel sharedInstanced].userId};
    [[AFAppDotNetAPIClient sharedClient] POST:@"/LaundryMall/Login_Registration/displayUserInformation.action" parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if ([responseObject[@"responseStatus"] isEqualToString:@"0"]) {
            NSDictionary *dic = responseObject[@"obj"];
            self.moneyLabel.text = [NSString stringWithFormat:@"%@",dic[@"balance"]];
            self.numberLabel.text = [NSString stringWithFormat:@"NO:%@",dic[@"cardNumber"]];
        }else{
            ShowMessage(responseObject[@"msg"]);
        }
        
        [self hiddenProgressHUD];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self showError:error];
        [self hiddenProgressHUD];
    }];
}

//支付
- (void)payEvent:(NSString *)strType{
    [self showprogressHUD];
    NSString *strMoney = @"0";
    if (chooseIndexPath == 0) {
        strMoney = @"500";
    }else if (chooseIndexPath == 1){
        strMoney = @"1000";
    }else if (chooseIndexPath == 2){
        strMoney = @"2000";
    }
    NSDictionary *parameters = @{@"uId":[UserModel sharedInstanced].userId,
                                 @"balance":strMoney,
                                 @"payType":strType,
                                 @"fromType":@"1"
                                 };
    [[AFAppDotNetAPIClient sharedClient] POST:@"LaundryMall/Balance_Order_Controller/addUserBalance.action" parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if ([responseObject[@"responseStatus"] isEqualToString:@"0"]) {
            if ([strType isEqualToString:@"0"]) {
                //微信支付
                [self weiXinpay:responseObject[@"data"]];
            }else if ([strType isEqualToString:@"1"]){
                //支付宝支付
                [self payByALiWithHandle:responseObject[@"data"][@"alSign"]];
            }
            
        }else{
            ShowMessage(responseObject[@"msg"]);
        }
        
        [self hiddenProgressHUD];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self showError:error];
        [self hiddenProgressHUD];
    }];
}

@end

//ui
@implementation MemberPrepaidPhoneViewController

- (void) viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self getData];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"会员充值";
    chooseIndexPath = 0;
    [self.view addSubview:self.tableView];
    
    //微信支付通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(WeChatPaySuccess) name:@"微信支付成功" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(WeChatForCancellation) name:@"微信支付用户中途取消" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(WeChatPaymentFailure) name:@"微信支付用户支付失败" object:nil];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark - init

- (UIView *)footView{
    if (!_footView) {
        _footView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 150 / WIDTH_5S_SCALE)];
        UIButton *typeButton = [[UIButton alloc]initWithFrame:CGRectMake(30 / WIDTH_5S_SCALE, 63 / WIDTH_5S_SCALE, SCREEN_WIDTH - 60 / WIDTH_5S_SCALE, 37 / WIDTH_5S_SCALE)];
        typeButton.titleLabel.font = DEF_FontSize_14;
        [typeButton setTitle:@"去充值" forState:UIControlStateNormal];
        typeButton.backgroundColor = getColor(mainColor);
        typeButton.layer.masksToBounds = YES;
        typeButton.layer.cornerRadius = 37 / WIDTH_5S_SCALE / 2;
        [typeButton setTitleColor:getColor(@"ffffff") forState:UIControlStateNormal];
        [typeButton addTarget:self action:@selector(typeButtonClick) forControlEvents:UIControlEventTouchUpInside];
        [_footView addSubview:typeButton];
    }
    return _footView;
}

- (UILabel *)numberLabel{
    if (!_numberLabel) {
        _numberLabel  = [[UILabel alloc]initWithFrame:CGRectMake(0, 130 / WIDTH_5S_SCALE, SCREEN_WIDTH - 62 / WIDTH_5S_SCALE - 20 / WIDTH_5S_SCALE, 30 / WIDTH_5S_SCALE)];
        _numberLabel.font = DEF_FontSize_14;
        _numberLabel.textColor = getColor(@"333333");
        _numberLabel.textAlignment = NSTextAlignmentRight;
        //_numberLabel.text = [NSString stringWithFormat:@"NO:%@",@"00000000"];
    }
    return _numberLabel;
}

- (UILabel *)moneyLabel{
    if (!_moneyLabel) {
        _moneyLabel = [[UILabel alloc]initWithFrame:CGRectMake(55 / WIDTH_5S_SCALE, 0, SCREEN_WIDTH - 120 / WIDTH_5S_SCALE, 191 / WIDTH_5S_SCALE - 28 / WIDTH_5S_SCALE)];
        _moneyLabel.font = [UIFont systemFontOfSize:50];
        _moneyLabel.textAlignment = NSTextAlignmentRight;
        _moneyLabel.textColor = getColor(@"ffffff");
        _moneyLabel.text = @"0.00";
        //_moneyLabel.attributedText = [self getAttributeName:@"0.00"];
    }
    return _moneyLabel;
}

- (UILabel *)balanceLabel{
    if (!_balanceLabel) {
        _balanceLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 55 / WIDTH_5S_SCALE,  191 / WIDTH_5S_SCALE - 28 / WIDTH_5S_SCALE)];
        _balanceLabel.font = DEF_FontSize_24;
        _balanceLabel.textColor = getColor(@"333333");
        _balanceLabel.textAlignment = NSTextAlignmentLeft;
        _balanceLabel.text = @"余额";
    }
    return _balanceLabel;
}

- (NSAttributedString *)getAttributeName:(NSString *)name{
    NSMutableAttributedString *attStr = [NSMutableAttributedString new];
    NSAttributedString *nameAtt = [[NSAttributedString alloc]initWithString:name attributes:@{NSForegroundColorAttributeName:getColor(@"ffffff") , NSFontAttributeName:[UIFont systemFontOfSize:56]}];
  
    //[attStr appendAttributedString:[[NSAttributedString alloc] initWithString:@"余额              "]];
    [attStr appendAttributedString:nameAtt];
    
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    [paragraphStyle setParagraphSpacing:26];//调整行间距
    [paragraphStyle setAlignment:NSTextAlignmentCenter];
    [attStr addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [attStr.mutableString length])];
    
    return attStr;
}

- (UIImageView *)titleImageView{
    if (!_titleImageView) {
        _titleImageView = [[UIImageView alloc]initWithFrame:CGRectMake(31 / WIDTH_5S_SCALE, 14 / WIDTH_5S_SCALE, SCREEN_WIDTH - 62 / WIDTH_5S_SCALE, 191 / WIDTH_5S_SCALE - 28 / WIDTH_5S_SCALE)];
        _titleImageView.contentMode = UIViewContentModeScaleAspectFit;
        _titleImageView.image = [UIImage imageNamed:@"my_MemberOfTheBackground"];
        
        _titleImageView.layer.shadowColor = [UIColor blackColor].CGColor;
        _titleImageView.layer.shadowRadius= 4;
        _titleImageView.layer.shadowOpacity = .5;
        _titleImageView.layer.shadowOffset = CGSizeMake(0, 3);//偏移距离
        [_titleImageView sd_addSubviews:@[self.balanceLabel, self.moneyLabel , self.numberLabel]];
    }
    return _titleImageView;
}

- (UIView *)headView{
    if (!_headView) {
        _headView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 191 / WIDTH_5S_SCALE)];
        _headView.backgroundColor = getColor(@"eeeeee");
        [_headView addSubview:self.titleImageView];
    }
    return _headView;
}

- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 64) style:UITableViewStyleGrouped];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.sectionFooterHeight = .01;
        _tableView.sectionHeaderHeight = .01;
        _tableView.tableFooterView = self.footView;
        _tableView.tableHeaderView = self.headView;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.showsHorizontalScrollIndicator = NO;
        _tableView.backgroundColor = getColor(@"ffffff");
    }
    return _tableView;
}

#pragma mark - click

- (void)typeButtonClick{
    __weak __typeof(self)weakSelf = self;
    MembersPayTopUpView *view = [[MembersPayTopUpView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT) selectedHandle:^(NSString *str) {
        //支付
        [weakSelf payEvent:str];
    }];
    [view show];
}

#pragma mark - <UITableViewDelegate , UITableViewDataSource>

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    MemberPrepaidPhoneTableViewCell *cell = [MemberPrepaidPhoneTableViewCell cellForTableView:tableView];
    cell.indexPath = indexPath;
    cell.chooseIndex = chooseIndexPath;
    cell.model = self.dataArray[indexPath.row];
    cell.getChooseIndexClick = ^{
        chooseIndexPath = (int)indexPath.row;
        [self.tableView reloadData];
    };
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    chooseIndexPath = (int)indexPath.row;
    [self.tableView reloadData];
}

#pragma mark - Event

/**
 支付宝支付
 
 @param orderString orderString description
 */
- (void)payByALiWithHandle:(NSString *)orderString{
    //应用注册scheme,在AliSDKDemo-Info.plist定义URL types
    NSString *appScheme = @"xiyialisdkdemo";
    // NOTE: 将签名成功字符串格式化为订单字符串,请严格按照该格式
    // NOTE: 调用支付结果开始支付
    [[AlipaySDK defaultService] payOrder:orderString fromScheme:appScheme callback:^(NSDictionary *resultDic) {
        NSLog(@"reslut = %@",resultDic);
        
        if ([resultDic[@"resultStatus"] isEqualToString:@"6001"]) {
            ShowMessage(resultDic[@"memo"]);
        }
        if ([resultDic[@"resultStatus"] isEqualToString:@"9000"]) {
            [self.view makeToast:@"支付成功!" duration:1 position:CSToastPositionCenter title:nil image:nil style:nil completion:^(BOOL didTap) {
                [self.navigationController popViewControllerAnimated:YES];
            }];
        }
    }];
}

/**
 微信支付
 */
- (void)weiXinpay:(NSDictionary *)dic{
    PayReq *request = [[PayReq alloc]init];
    request.partnerId = dic[@"partnerid"];
    request.prepayId= dic[@"prepayid"];
    request.package = dic[@"package"];
    request.nonceStr= dic[@"noncestr"];
    request.timeStamp= [dic[@"timestamp"] intValue];
    request.sign= dic[@"sign"];
    [WXApi sendReq:request];
}

//通知执行事件
/**
 微信支付成功
 */
- (void)WeChatPaySuccess{
    [self.view makeToast:@"支付成功!" duration:1 position:CSToastPositionCenter title:nil image:nil style:nil completion:^(BOOL didTap) {
        [self.navigationController popViewControllerAnimated:YES];
    }];
}
/**
 微信支付用户中途取消
 */
- (void)WeChatForCancellation{
    ShowMessage(@"用户中途取消");
}
/**
 微信支付用户支付失败
 */
- (void)WeChatPaymentFailure{
    ShowMessage(@"支付失败");
}


#pragma mark - data

- (NSMutableArray *)dataArray{
    if (!_dataArray) {
        _dataArray  = @[@{@"title":@"500"},
                        @{@"title":@"1000"},
                        @{@"title":@"2000"},
                        ].mutableCopy;
    }
    return _dataArray;
}



@end
